package com.cheyunkeji.er.fragment.evaluate;

import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.activity.evaluate.EvaluateWorkflowActivity;
import com.cheyunkeji.er.base.BaseFragment;
import com.cheyunkeji.er.bean.evaluate.EvaluateDetailResult2;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.view.SToast;
import com.google.gson.Gson;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by Michael on 2017/3/29 10:58.
 */

public class CarConfigInfoFragment extends BaseFragment implements EvaluateWorkflowActivity.OnOutActionListener {

    public static final int PAGE_INDEX = 2;
    private static final String TAG = CarConfigInfoFragment.class.getSimpleName();
    @BindView(R.id.cb_tc)
    CheckBox cbTc;
    @BindView(R.id.cb_abs)
    CheckBox cbAbs;
    @BindView(R.id.cb_dd_hsj)
    CheckBox cbDdHsj;
    @BindView(R.id.cb_fdq)
    CheckBox cbFdq;
    @BindView(R.id.cb_tq)
    CheckBox cbTq;
    @BindView(R.id.cb_zddc)
    CheckBox cbZddc;
    @BindView(R.id.cb_ds_xh)
    CheckBox cbDsXh;
    @BindView(R.id.cb_zn_ys)
    CheckBox cbZnYs;
    @BindView(R.id.cb_yx_zj)
    CheckBox cbYxZj;
    @BindView(R.id.cb_dvd)
    CheckBox cbDvd;
    @BindView(R.id.cb_tv)
    CheckBox cbTv;
    @BindView(R.id.ll_checkboxs_left)
    LinearLayout llCheckboxsLeft;
    @BindView(R.id.cb_py)
    CheckBox cbPy;
    @BindView(R.id.cb_dd_zy)
    CheckBox cbDdZy;
    @BindView(R.id.cb_lhj_lg)
    CheckBox cbLhjLg;
    @BindView(R.id.cb_dlzx)
    CheckBox cbDlzx;
    @BindView(R.id.cb_dc_ld)
    CheckBox cbDcLd;
    @BindView(R.id.cb_dc_xy)
    CheckBox cbDcXy;
    @BindView(R.id.cb_wx_dh)
    CheckBox cbWxDh;
    @BindView(R.id.cb_cs_mp)
    CheckBox cbCsMp;
    @BindView(R.id.cb_cd)
    CheckBox cbCd;
    @BindView(R.id.cb_mp3)
    CheckBox cbMp3;
    @BindView(R.id.cb_xc_jly)
    CheckBox cbXcJly;
    @BindView(R.id.ll_checkboxs_right)
    LinearLayout llCheckboxsRight;
    @BindView(R.id.et_qn_count)
    EditText etQnCount;
    @BindView(R.id.et_ktk_count)
    EditText etKtkCount;
    @BindView(R.id.et_ddm_count)
    EditText etDdmCount;
    @BindView(R.id.et_yjp_count)
    EditText etYjpCount;
    @BindView(R.id.iv_goto_top)
    ImageView ivGotoTop;
    @BindView(R.id.tv_previous_step)
    TextView tvPreviousStep;
    @BindView(R.id.tv_next_step)
    TextView tvNextStep;
    @BindView(R.id.sv_content)
    ScrollView svContent;
    private EvaluateDetailResult2 evaluateResult;
    private Runnable mTask;

    @Override
    protected void doInflaterView(LayoutInflater inflater, ViewGroup container) {

        contentView = inflater.inflate(R.layout.er_frag_car_config_info_layout, container, false);
        ButterKnife.bind(this, contentView);
    }

    @Override
    protected void init() {

    }

    @Override
    protected void initView() {

        ivGotoTop.setOnClickListener(this);
        tvPreviousStep.setOnClickListener(this);
        tvNextStep.setOnClickListener(this);

    }

    @Override
    protected void initData() {

        evaluateResult = MyApplication.getInstance().getEvaluateResult();

        if (null != evaluateResult) {
            displayInfo();
        }
    }

    private void displayInfo() {


        if (!TextUtils.isEmpty(evaluateResult.getSunroof())) {
            cbTc.setChecked(evaluateResult.getSunroof().equals("1"));
        }
        if (!TextUtils.isEmpty(evaluateResult.getAbs())) {
            cbAbs.setChecked(evaluateResult.getAbs().equals("1"));
        }
        if (!TextUtils.isEmpty(evaluateResult.getPdmirrors())) {
            cbDdHsj.setChecked(evaluateResult.getPdmirrors().equals("1"));
        }
        if (!TextUtils.isEmpty(evaluateResult.getCaralarm())) {
            cbFdq.setChecked(evaluateResult.getCaralarm().equals("1"));
        }
        if (!TextUtils.isEmpty(evaluateResult.getSteelwheels())) {
            cbTq.setChecked(evaluateResult.getSteelwheels().equals("1"));
        }
        if (!TextUtils.isEmpty(evaluateResult.getPav())) {
            cbZddc.setChecked(evaluateResult.getPav().equals("1"));
        }
        if (!TextUtils.isEmpty(evaluateResult.getCcs())) {
            cbDsXh.setChecked(evaluateResult.getCcs().equals("1"));
        }
        if (!TextUtils.isEmpty(evaluateResult.getSmartkey())) {
            cbZnYs.setChecked(evaluateResult.getSmartkey().equals("1"));
        }
        if (!TextUtils.isEmpty(evaluateResult.getSpeker())) {
            cbYxZj.setChecked(evaluateResult.getSpeker().equals("1"));
        }
        if (!TextUtils.isEmpty(evaluateResult.getDvd())) {
            cbDvd.setChecked(evaluateResult.getDvd().equals("1"));
        }
        if (!TextUtils.isEmpty(evaluateResult.getAbs())) {
            cbTv.setChecked(evaluateResult.getCmtv().equals("1"));
        }
        if (!TextUtils.isEmpty(evaluateResult.getAbs())) {
            cbPy.setChecked(evaluateResult.getLeatherchair().equals("1"));
        }

        if (!TextUtils.isEmpty(evaluateResult.getAutochair())) {
            cbDdZy.setChecked(evaluateResult.getAutochair().equals("1"));
        }
        if (!TextUtils.isEmpty(evaluateResult.getAlloywheel())) {
            cbLhjLg.setChecked(evaluateResult.getAlloywheel().equals("1"));
        }
        if (!TextUtils.isEmpty(evaluateResult.getAbs())) {
            cbPy.setChecked(evaluateResult.getLeatherchair().equals("1"));
        }
        if (!TextUtils.isEmpty(evaluateResult.getPps())) {
            cbDlzx.setChecked(evaluateResult.getPps().equals("1"));
        }
        if (!TextUtils.isEmpty(evaluateResult.getPdc())) {
            cbDcLd.setChecked(evaluateResult.getPdc().equals("1"));
        }
        if (!TextUtils.isEmpty(evaluateResult.getReverseimg())) {
            cbDcXy.setChecked(evaluateResult.getReverseimg().equals("1"));
        }
        if (!TextUtils.isEmpty(evaluateResult.getAvigation())) {
            cbWxDh.setChecked(evaluateResult.getAvigation().equals("1"));
        }
        if (!TextUtils.isEmpty(evaluateResult.getEmblem())) {
            cbCsMp.setChecked(evaluateResult.getEmblem().equals("1"));
        }
        if (!TextUtils.isEmpty(evaluateResult.getCd())) {
            cbCd.setChecked(evaluateResult.getCd().equals("1"));
        }
        if (!TextUtils.isEmpty(evaluateResult.getAbs())) {
            cbMp3.setChecked(evaluateResult.getAbs().equals("1"));
        }
        if (!TextUtils.isEmpty(evaluateResult.getCardvr())) {
            cbXcJly.setChecked(evaluateResult.getCardvr().equals("1"));
        }

        if (!TextUtils.isEmpty(evaluateResult.getAirbag()) && 0 != Integer.valueOf(evaluateResult.getAirbag()))
            etQnCount.setText(evaluateResult.getAirbag());

        if (!TextUtils.isEmpty(evaluateResult.getAcnum()) && 0 != Integer.valueOf(evaluateResult.getAcnum()))
            etKtkCount.setText(evaluateResult.getAcnum());

        if (!TextUtils.isEmpty(evaluateResult.getAutodoor()) && 0 != Integer.valueOf(evaluateResult.getAutodoor()))
            etDdmCount.setText(evaluateResult.getAutodoor());

        if (!TextUtils.isEmpty(evaluateResult.getLcdnum()) && 0 != Integer.valueOf(evaluateResult.getLcdnum()))
            etYjpCount.setText(evaluateResult.getLcdnum());

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_previous_step:
                onSaveEvaluateResult(new Runnable() {
                    @Override
                    public void run() {
                        goToPreviousPage();
                    }
                });
                break;
            case R.id.tv_next_step:
                onSaveEvaluateResult(new Runnable() {
                    @Override
                    public void run() {
                        goToNextPage();
                    }
                });
                break;
            case R.id.iv_goto_top:
                svContent.smoothScrollTo(0, 0);
                break;

            default:
                break;
        }
    }

    private void goToPreviousPage() {
        ((EvaluateWorkflowActivity) getActivity()).setCurrentPage(CarBaseInfoFragment.PAGE_INDEX);
    }

    @Override
    public void onSaveEvaluateResult(Runnable task) {

        if (null != task)
            this.mTask = task;

        HashMap<String, String> params = new HashMap<>();
//        params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());

        params.put("sunroof", String.valueOf(cbTc.isChecked() ? 1 : 0));
        params.put("abs", String.valueOf(cbAbs.isChecked() ? 1 : 0));
        params.put("pdmirrors", String.valueOf(cbDdHsj.isChecked() ? 1 : 0));
        params.put("caralarm", String.valueOf(cbFdq.isChecked() ? 1 : 0));
        params.put("steelwheels", String.valueOf(cbTq.isChecked() ? 1 : 0));
        params.put("pav", String.valueOf(cbZddc.isChecked() ? 1 : 0));
        params.put("ccs", String.valueOf(cbDsXh.isChecked() ? 1 : 0));
        params.put("smartkey", String.valueOf(cbZnYs.isChecked() ? 1 : 0));
        params.put("speker", String.valueOf(cbYxZj.isChecked() ? 1 : 0));
        params.put("dvd", String.valueOf(cbDvd.isChecked() ? 1 : 0));
        params.put("cmtv", String.valueOf(cbTv.isChecked() ? 1 : 0));
        params.put("leatherchair", String.valueOf(cbPy.isChecked() ? 1 : 0));
        params.put("autochair", String.valueOf(cbDdZy.isChecked() ? 1 : 0));
        params.put("alloywheel", String.valueOf(cbLhjLg.isChecked() ? 1 : 0));
        params.put("pps", String.valueOf(cbDlzx.isChecked() ? 1 : 0));
        params.put("pdc", String.valueOf(cbDcLd.isChecked() ? 1 : 0));
        params.put("reverseimg", String.valueOf(cbDcXy.isChecked() ? 1 : 0));
        params.put("avigation", String.valueOf(cbWxDh.isChecked() ? 1 : 0));
        params.put("emblem", String.valueOf(cbCsMp.isChecked() ? 1 : 0));
        params.put("cd", String.valueOf(cbCd.isChecked() ? 1 : 0));
        params.put("mp3", String.valueOf(cbMp3.isChecked() ? 1 : 0));
        params.put("pdmirrors", String.valueOf(cbDdHsj.isChecked() ? 1 : 0));
        params.put("cardvr", String.valueOf(cbXcJly.isChecked() ? 1 : 0));

        params.put("airbag", etQnCount.getText().toString());
        params.put("acnum", etKtkCount.getText().toString());
        params.put("autodoor", etDdmCount.getText().toString());
        params.put("lcdnum", etYjpCount.getText().toString());

        if (!TextUtils.isEmpty(evaluateResult.getAid()))
            params.put("aid", evaluateResult.getAid());

        if (MyApplication.getInstance().getEvaluateResult() == null || MyApplication.getInstance().getEvaluateResult().getIroute() == null || MyApplication.getInstance().getEvaluateResult().getIroute().size() == 0) {
            int[] iroute = new int[15];
            iroute[PAGE_INDEX] = 1;
            String json = new Gson().toJson(iroute);
            Log.e(TAG, "saveData: 评估记录为空或数组为空时 保存记录数组 ：  " + json.substring(1, json.length() - 1));
            params.put("iroute", json.substring(1, json.length() - 1));
        } else {
            MyApplication.getInstance().getEvaluateResult().getIroute().set(PAGE_INDEX, 1);
            String json = new Gson().toJson(MyApplication.getInstance().getEvaluateResult().getIroute());
            params.put("iroute", json.substring(1, json.length() - 1));
            Log.e(TAG, "saveData:  保存记录数组 ：记录非空并且数组非空时 保存记录数组 ：   " + json.substring(1, json.length() - 1));
        }


        for (String key : params.keySet()) {

            Log.e(TAG, "onSaveEvaluateResult: " + " key : " + key + "   value : " + params.get(key));
        }

        //        根据评估类型进行保存或编辑
        int evaluateType = ((EvaluateWorkflowActivity) getActivity()).getEvaluateArchiveType();

//       保存新创建、未上传待评估数据
        if (evaluateType == Constants.ARCHIVE_TYPE_CREATE_NEW_EVALUATE || evaluateType == Constants.ARCHIVE_TYPE_UN_UPLOAD_TO_EVALUATE || evaluateType == Constants.ARCHIVE_TYPE_WITH_FAST_EVALUATE_VIN) {

            ApiClient.postForm(((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL(), params, new RespCallback<EvaluateDetailResult2>() {

                @Override
                protected void onRequestFailed(String msg) {
                    SToast.show(msg);
                    if (mTask instanceof EvaluateWorkflowActivity.ExitRunnable) {
                        mTask.run();
                        mTask = null;
                    }
                }

                @Override
                protected void onSuccess(EvaluateDetailResult2 data) {

                    if (null != data) {

                        MyApplication.getInstance().setEvaluateResult(data);
                        if (null != mTask) {
                            mTask.run();
                            mTask = null;
                        }
                    }
                }

                @Override
                public void onBefore(Request request, int id) {
                    showDialog();
                }

                @Override
                public void onAfter(int id) {
                    dismissDialog();
                }
            });

        } else if (evaluateType == Constants.ARCHIVE_TYPE_UPLOADED_TO_EDIT) {

            ApiClient.postForm(((EvaluateWorkflowActivity) getActivity()).getCURRENT_TO_UPLOAD_RESULT_URL(), params, new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {

                    // 网络异常
                    if (e instanceof UnknownHostException || e instanceof SocketException) {
                        SToast.show(R.string.tip_network_error, Gravity.CENTER);
                        return;
                    }
                }

                @Override
                public void onResponse(String response, int id) {

                    try {

                        JSONObject obj = new JSONObject(response);
                        if (obj.optInt("code") == 1) {
//                            SToast.show("保存成功", Gravity.CENTER);

                            Log.e(TAG, "onResponse: 编辑成功 : " + obj.optString("data"));

                            if (null != mTask) {
                                mTask.run();
                                mTask = null;
                            }

                        } else {
                            SToast.show( obj.optString("msg") );
                            if (mTask instanceof EvaluateWorkflowActivity.ExitRunnable) {
                                mTask.run();
                                mTask = null;
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onBefore(Request request, int id) {
                    showDialog();
                }

                @Override
                public void onAfter(int id) {
                    dismissDialog();
                }
            });

        }
    }

    private void goToNextPage() {
        ((EvaluateWorkflowActivity) getActivity()).setCurrentPage(TakeCarPhotoFragment.PAGE_INDEX);
    }
}
